package com.example.demo.components;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @version : 1.0
 * 撸代码前，多思考一点
 * @author: pengzx
 * @Description: 上下文容器感知接口, 还有一些其他感知接口，都是以Aware结尾，官方不建议用这些接口。因为会打破控制反转，并且会把自己的代码耦合到spring中
 * @date: 11:31 2018/5/31
 */
@Component
public class DemoAware implements ApplicationContextAware {
    private static ApplicationContext APPLICATIONCONTEXT;

    public static <T> T getBean(String name)
    {

        Object object = null;
        try {
            object = DemoAware.APPLICATIONCONTEXT.getBean(name);
        } catch (BeansException e) {
            System.out.println(e.toString());
        }
        return (T) object;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        APPLICATIONCONTEXT = applicationContext;
    }
}
